﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using System.Collections.Generic;

public partial class Client_UserControl_ucShoppingCart : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblCheckOutInfo.Text = "";
        try
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    private void LoadData()
    {
        int iNoOfItems = LoadCart();
        decimal dTotalAmount = SetTotalAmount();
        ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);

        if (Session[Global.SESSION_CART] == null)
            pnlCartFooter.Visible = false;
    }
    private int LoadCart()
    {
        try
        {
            //ArrayList arrItems = (ArrayList)Session[Global.SESSION_CART];

            List<TblOrderDetail> arrItems = new List<TblOrderDetail>();
            if (Session[Global.SESSION_CART] != null)
                arrItems = (List<TblOrderDetail>)Session[Global.SESSION_CART];

            int iNoOfItems = 0;
            double dTotalAmount = 0;

            foreach (TblOrderDetail order in arrItems)
            {
                iNoOfItems += order.Quantity;
                //dTotalAmount += order.TotalAmount;
                dTotalAmount += order.Quantity * order.Price;
            }
            SetNumberOfItems(iNoOfItems);

            grdShoppingCart.DataSource = arrItems;
            grdShoppingCart.DataBind();

            return iNoOfItems;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void SetNumberOfItems(int ItemsNumber)
    {
        lblNumber.Text = ItemsNumber.ToString() + " sản phẩm";
        //pnlCartFooter.Visible = true;
        if (ItemsNumber == 0)
        {
            tdShoppingCart.Attributes["class"] = "shoppingCartEmptyS";
            //pnlCartFooter.Visible = false;
        }
        if (ItemsNumber == 1)
        {
            lblNumber.Text = ItemsNumber.ToString() + " sản phẩm";
            tdShoppingCart.Attributes["class"] = "shoppingCartHalfS";
        }
        if (ItemsNumber == 2)
            tdShoppingCart.Attributes["class"] = "shoppingCartFullS";
        if (ItemsNumber > 2)
            tdShoppingCart.Attributes["class"] = "shoppingCartFullMoreS";
    }
    private decimal SetTotalAmount()
    {
        try
        {
            decimal dTotalAmount = 0;
            for (int i = 0; i < grdShoppingCart.Rows.Count; i++)
            {
                Label lblSubTotal = (Label)grdShoppingCart.Rows[i].Cells[4].FindControl("lblSubTotal");
                if (lblSubTotal != null)
                {
                    try
                    {
                        dTotalAmount += Convert.ToDecimal(lblSubTotal.Text.Trim());
                    }
                    catch (Exception) { }
                }
            }

            lblTotal.Text = dTotalAmount.ToString("0,00.##");

            Session[Global.SESSION_TOTAL] = dTotalAmount;

            return dTotalAmount;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static void BindGridView(GridViewRow gridViewRow)
    {
        Label lblPrice = (Label)gridViewRow.Cells[2].FindControl("lblPrice");
        Label lblMatchedPrice = (Label)gridViewRow.Cells[2].FindControl("lblMatchedPrice");
        TextBox txtQuantity = (TextBox)gridViewRow.Cells[3].FindControl("txtQuantity");
        Label lblSubTotal = (Label)gridViewRow.Cells[4].FindControl("lblSubTotal");

        double dPrice = 0;
        double dMatchedPrice = 0;
        int iQuantity = 0;
        try
        {
            dPrice = Convert.ToDouble(lblPrice.Text.Trim().Replace("$", ""));
            dMatchedPrice = Convert.ToDouble(lblMatchedPrice.Text.Trim().Replace("$", ""));
            iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
        }
        catch (Exception) { }
        double dSubTotal = 0;

        lblPrice.Text = dPrice.ToString("0,00.##");
        if (dMatchedPrice == 0)
        {
            dSubTotal = dPrice * iQuantity;
            lblPrice.Text = dPrice.ToString("0,00.##");
            lblMatchedPrice.Visible = false;
        }
        else
        {
            dSubTotal = dMatchedPrice * iQuantity;
            lblPrice.CssClass = "clsPriceCartCrossed";
            lblMatchedPrice.Text = "\r\n" + dMatchedPrice.ToString("0,00.##");
            lblMatchedPrice.Visible = true;
        }

        lblSubTotal.Text = dSubTotal.ToString("0,00.##");

        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            //ImageButton imgButton = (ImageButton)gridViewRow.Cells[5].FindControl("imgDelete");
            //gridViewRow.Attributes["onmouseover"] = "$('#" + imgButton.ClientID + "').show();";
            //gridViewRow.Attributes["onmouseout"] = "$('#" + imgButton.ClientID + "').hide();";
        }
    }

    protected void grdShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            GridViewRow gridViewRow = e.Row;
            BindGridView(gridViewRow);
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    protected void btnQuantity_Click(object sender, EventArgs e)
    {
        try
        {
            ImageButton btnQuantity = (ImageButton)sender;
            if (btnQuantity != null)
            {
                string strUniqueID = btnQuantity.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[4].Replace("ctl", "")) - 2);
                GridViewRow gridRow = grdShoppingCart.Rows[iRowIndex];
                if (gridRow != null)
                {
                    Control ctlTxtQuantity = gridRow.Cells[3].FindControl("txtQuantity");
                    if (ctlTxtQuantity != null)
                    {
                        int iNoOfItems = 0;
                        if (Session[Global.SESSION_CART] != null)
                        {

                            List<TblOrderDetail> arrProducts = (List<TblOrderDetail>)Session[Global.SESSION_CART];
                            TblOrderDetail order = arrProducts[iRowIndex];
                            TextBox txtQuantity = (TextBox)ctlTxtQuantity;
                            string strQuantity = txtQuantity.Text.Trim();
                            int iQuantityUpdated = order.Quantity;
                            try
                            {
                                int iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
                                if (btnQuantity.SkinID.Contains("Up"))
                                    iQuantityUpdated = iQuantity + 1;
                                if (btnQuantity.SkinID.Contains("Dn"))
                                    iQuantityUpdated = iQuantity - 1;
                                if (iQuantityUpdated == 0) iQuantityUpdated = 1;
                            }
                            catch (Exception) { }

                            txtQuantity.Text = iQuantityUpdated.ToString();

                            BindGridView(gridRow);

                            order.Quantity = iQuantityUpdated;

                            //Set number of items
                            for (int i = 0; i < arrProducts.Count; i++)
                            {
                                TblOrderDetail pOrder = (TblOrderDetail)arrProducts[i];
                                iNoOfItems += pOrder.Quantity;
                            }
                            SetNumberOfItems(iNoOfItems);
                        }

                        decimal dTotalAmount = SetTotalAmount();

                        ScriptManager.RegisterStartupScript(pnlShoppingCart, pnlShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        try
        {
            TextBox txtQuantity = (TextBox)sender;
            if (txtQuantity != null)
            {
                string strUniqueID = txtQuantity.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[4].Replace("ctl", "")) - 2);
                GridViewRow gridRow = grdShoppingCart.Rows[iRowIndex];
                if (gridRow != null)
                {
                    int iNoOfItems = 0;
                    if (Session[Global.SESSION_CART] != null)
                    {
                        

                        List<TblOrderDetail> arrProducts = (List<TblOrderDetail>)Session[Global.SESSION_CART];
                        TblOrderDetail order = arrProducts[iRowIndex];

                        string strQuantity = txtQuantity.Text.Trim();
                        int iQuantity = order.Quantity;
                        try
                        {
                            iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
                            if (iQuantity <= 0)
                                iQuantity = order.Quantity;
                        }
                        catch (Exception) { }

                        txtQuantity.Text = iQuantity.ToString();

                        BindGridView(gridRow);

                        order.Quantity = iQuantity;

                        //Set number of items       
                        for (int i = 0; i < arrProducts.Count; i++)
                        {
                            TblOrderDetail pOrder = (TblOrderDetail)arrProducts[i];
                            iNoOfItems += pOrder.Quantity;
                        }
                        SetNumberOfItems(iNoOfItems);
                    }

                    decimal dTotalAmount = SetTotalAmount();

                    ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    protected void imgDelete_Click(object sender, EventArgs e)
    {
        try
        {
            ImageButton imgDel = (ImageButton)sender;
            if (imgDel != null)
            {
                string strUniqueID = imgDel.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[4].Replace("ctl", "")) - 2);

                if (Session[Global.SESSION_CART] != null)
                {
                    List<TblOrderDetail> arrProducts = (List<TblOrderDetail>)Session[Global.SESSION_CART];
                    //ScriptManager.RegisterStartupScript(pnlShoppingCart, pnlShoppingCart.GetType(), "scriptalert", "alert('" + iRowIndex.ToString() + "');", true);                 
                    arrProducts.RemoveAt(iRowIndex);
                    int iNoOfItems = LoadCart();
                    decimal dTotalAmount = SetTotalAmount();

                    ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("c") + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
    }

    protected void imgBtnCheckOut_Click(object sender, ImageClickEventArgs e)
    {
        //if (Session[Global.SESSION_LOGGED_USER] == null)
        //{
        //    Response.Redirect("~/Login.aspx", true);
        //    return;
        //}

        /*
        try
        {
            if (Session[Global.SESSION_CART] != null)
            {
                OrderDAO orderdao = new OrderDAO(Global.CONNECTION_STRING);
                TblOrder order = new TblOrder();
                //TblUserAccount userAccount = (TblUserAccount)Session[Global.SESSION_LOGGED_USER];
                //order.User = userAccount;

                List<TblOrderDetail> arrItems = (List<TblOrderDetail>)Session[Global.SESSION_CART];
                int id = orderdao.Insert(order, arrItems);

                Session[Global.SESSION_CART] = null;
                ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('0|0');", true);

                //TranferOrder tranfer = new TranferOrder(Global.CONNECTION_STRING, Global.MYOB_CONNECTION_STRING);

                //MYOBOrder myobOrder = new MYOBOrder();
                //myobOrder.CoLastName = Global.MYOB_DEFAULT_CUSTOMER_NAME;
                //myobOrder.SaleStatus = "O";

                //////tranfer.Insert(id);
                //tranfer.InsertOrder(id, myobOrder);

                //LoadData();
                lblCheckOutInfo.Text = "Check Out Success";
                Response.Redirect(string.Format("~/ShippingTo.aspx?ID={0}", id.ToString()), false);
                //Server.Transfer("~/ShippingTo.aspx");
            }
            else
            {
                LoadData();
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
         * */

        if (Session[Global.SESSION_LOGGED_USER] == null)
        {
            Response.Redirect(string.Format("~/LoginOrRegister.aspx"), false);
            return;
        }
        Response.Redirect(string.Format("~/ShippingTo.aspx"), false);
    } 
}
